//
//  FoodHealthViewController.m
//  厨房助手
//
//  Created by 0.0 on 15-4-13.
//  Copyright (c) 2015年 dingjun. All rights reserved.
//

#import "FoodHealthViewController.h"
#import "SecondViewController.h"
#import "FirstModel.h"
#import "FirstTableViewCell.h"


#define DisesURL @"http://121.41.87.4:80/HandheldKitchen/api/vegetable/tbloffice!getOffice.do"

@interface FoodHealthViewController () <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>
{
    UITableView *_tableView;
    
    NSInteger _successNum;
    
    
    UIAlertView *_alertView;
}

@property (nonatomic, retain) NSMutableArray *firstArray;
@property (nonatomic, retain) NSTimer *timer;

@end

@implementation FoodHealthViewController

- (void)dealloc
{
    [_firstArray release];
    
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        self.firstArray = [NSMutableArray array];
        _successNum = 0;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 获取navigationBar的信息
    [self createNavigationBar];
    
    [self creatBackground];
    
    // 创建TableView
    [self createTabelView];
    
    // 创建判断是否加载成功的view（如果失败则重新加载）
    [self timerForSuccess];
    
}

- (void)timerForSuccess
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(successNet) userInfo:nil repeats:YES];
}

- (void)creatBackground
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64)];
    [imageView setImage:[UIImage imageNamed:@"secondBarBacground.jpg"]];
    [self.view addSubview:imageView];
    [imageView release];
}

- (void)createNavigationBar
{
//    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.navigationItem.title = @"科室名称";
}

- (void)createTabelView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64 - 44) style:UITableViewStylePlain];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[FirstTableViewCell class] forCellReuseIdentifier:@"cell1"];
    _tableView.rowHeight = 80;
    
    _tableView.separatorColor = [UIColor whiteColor];
    [_tableView setBackgroundColor:[UIColor clearColor]];
    
    [self.view addSubview:_tableView];
    [_tableView release];
    // 创建完成请求数据
    [self startConnect];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.firstArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
    
    FirstModel *model = [self.firstArray objectAtIndex:indexPath.row];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"png"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    [cell.firstImageView sd_setImageWithURL:[NSURL URLWithString:model.imagePath] placeholderImage:image];
    [cell.firstNameLabel setText:model.officeName];
    [cell.firstDiseaseLabel setText:[NSString stringWithFormat:@"%@...", model.diseaseNames]];
    
    [cell setBackgroundColor:[UIColor clearColor]];
    cell.firstNameLabel.textColor = [UIColor whiteColor];
    cell.firstDiseaseLabel.textColor = [UIColor whiteColor];
    
    return cell;
}


- (void)startConnect
{
    NSDictionary *dic = @{@"phonetype":@"2", @"is_traditional":@"0"};
    
    __block NSMutableArray *myArray = self.firstArray;
    __block UITableView *myTableView = _tableView;
    [MyConnection connectWithUrl:DisesURL parmaters:dic finishBlock:^(NSData *data) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = dataDic[@"data"];
        for (NSDictionary *aDic in array) {
            FirstModel *model = [FirstModel firstModelWithOfficeId:aDic[@"officeId"] officeName:aDic[@"officeName"] diseaseNames:aDic[@"diseaseNames"] imagePath:aDic[@"imagePath"]];
            [myArray addObject:model];
            [myTableView reloadData];
        }
        
    }];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    FirstModel *model = [self.firstArray objectAtIndex:indexPath.row];
    
    SecondViewController *secondView = [SecondViewController secondViewControllerWithOfficeId:model.officeId];
    [self.navigationController pushViewController:secondView animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *my = [[tableView indexPathsForVisibleRows] firstObject];
    if (indexPath.row == my.row) {
        _successNum = 1;
    }
}

- (void)successNet
{
    [_timer invalidate];
    // 如果是0代表数据没请求回来
    if (_successNum == 0) {
        _alertView = [[UIAlertView alloc] initWithTitle:@"加载失败" message:@"是否重新加载" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [_alertView show];
        
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [_alertView dismissWithClickedButtonIndex:0 animated:YES];
        [_alertView release];
        [self successNet];
        [self startConnect];
    }
    
    if (buttonIndex == 0) {
        [_alertView dismissWithClickedButtonIndex:0 animated:YES];
        [_alertView release];
    }
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
